package com.baiduspring.service.resourcecollection.impl;

import com.baiduspring.dao.entity.ResourceCollection;
import com.baiduspring.dao.mapper.ResourceCollectionMapper;
import com.baiduspring.error.BaiduSpringException;
import com.baiduspring.service.resourcecollection.ResourceCollectionService;
import com.baiduspring.service.resourcecollection.RollBack;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.Optional;

/**
 * 资源收藏相关接口实现
 *
 * @author xiongyan
 */
@Service
@Slf4j
public class ResourceCollectionServiceImpl implements ResourceCollectionService {
    @Resource
    private ResourceCollectionMapper resourceCollectionMapper;

    @Override
    public void add(ResourceCollection resourceCollection, RollBack rollBack) {
        ResourceCollection result = resourceCollectionMapper.selectOneBySelective(resourceCollection);
        if (Objects.nonNull(result)) {
            throw new BaiduSpringException("您已经收藏，不能重复");
        }

        resourceCollection.setCreateDate(System.currentTimeMillis());

        try {
            int rows = resourceCollectionMapper.insertSelective(resourceCollection);
            if (rows > 0) {
                rollBack.execute();
            }
        } catch (BaiduSpringException e) {
            log.error("添加资源收藏错误：{}", e);
            throw e;
        }
    }

    @Override
    public Optional<ResourceCollection> get(ResourceCollection resourceCollection) {
        ResourceCollection resourceCollection1 = resourceCollectionMapper.selectOneBySelective(resourceCollection);
        return Optional.ofNullable(resourceCollection1);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void cancel(ResourceCollection resourceCollection, RollBack rollBack) {
        ResourceCollection result = resourceCollectionMapper.selectOneBySelective(resourceCollection);
        if (Objects.nonNull(result)) {
            try {
                int rows = resourceCollectionMapper.deleteByPrimaryKey(result.getId());
                if (rows > 0) {
                    rollBack.execute();
                }
            } catch (BaiduSpringException e) {
                log.error("取消收藏错误：{}", e);
                throw e;
            }
        }
    }
}
